package com.yunmai.library.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.yunmai.library.db.upgrade.IDatabaseUpgrade;
import java.sql.SQLException;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author liyi
 *         create at 2018/3/26
 **/
public class DBOpenHelper extends OrmLiteSqliteOpenHelper {

    private static DBOpenHelper instance;
    private CopyOnWriteArrayList<AbstractDBChange<?>> changeList =
        new CopyOnWriteArrayList<>();

    private Map<String, Dao> daos = new HashMap<String, Dao>();

    /**
     *
     */
    private Map<Integer,IDatabaseUpgrade> mUpgradeMaps = new TreeMap(
        new Comparator<Integer>() {
            @Override public int compare(Integer o1, Integer o2) {
                return o1 - o2;
            }
        }
    );

    private DBOpenHelperListener dbOpenHelperListener;

    public static String DB_NAME = "db";
    public static int DB_VERSION = 1;

    private DBOpenHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }

    /**
     * 单例获取该Helper
     *
     * @param context
     * @return
     */
    public static DBOpenHelper getInstance(Context context) {
        context = context.getApplicationContext();
        if (instance == null) {
            synchronized (DBOpenHelper.class) {
                if (instance == null)
                    instance = new DBOpenHelper(context);
            }
        }

        return instance;
    }

    /**
     * 增加一个监听器
     *
     * @param listener void
     */
    public <T> void addChangeListener(AbstractDBChange<T> listener) {
        if (listener != null && !changeList.contains(listener))
            changeList.add(listener);
    }

    public List<AbstractDBChange<?>> getChangeListenerList() {
        return changeList;
    }

    /**
     * 移除一个监听器
     *
     * @param listener void
     */
    public <T> void removeChangeListener(AbstractDBChange<T> listener) {
        if (listener != null && changeList.contains(listener)) {
            changeList.remove(listener);
        }
    }

    public void setDbOpenHelperListener(DBOpenHelperListener dbOpenHelperListener) {
        this.dbOpenHelperListener = dbOpenHelperListener;
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource) {
        if (dbOpenHelperListener != null) {
            dbOpenHelperListener.onCreate(connectionSource);
        }
    }



    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource,
                          int oldVersion, int newVersion) {
        Iterator<Map.Entry<Integer,IDatabaseUpgrade>> iterator = mUpgradeMaps.entrySet().iterator();

        boolean needUpgrade = false;

        while (iterator.hasNext()){
            Map.Entry<Integer,IDatabaseUpgrade> entry = iterator.next();
            if (entry.getKey() == oldVersion){
                needUpgrade = true;
            }
            if (needUpgrade){
                entry.getValue().onUpgrade(connectionSource,oldVersion,newVersion);
            }
        }
        if (!needUpgrade && dbOpenHelperListener != null) {
            dbOpenHelperListener.onClearDatebase();
        }
    }

    public void addDataBaseUpgrade(int versionCOde,IDatabaseUpgrade databaseUpgrade){
        mUpgradeMaps.put(versionCOde,databaseUpgrade);
    }

    /**
     * 释放资源
     */
    @Override
    public void close() {
        super.close();

        for (String key : daos.keySet()) {
            Dao dao = daos.get(key);
            dao = null;
        }
    }

    public ConnectionSource getConnectionSource() {
        return connectionSource;
    }

    public <D extends Dao<T, ?>, T> D getDao(Class<T> clazz) throws SQLException {
        Dao dao = null;
        String className = clazz.getSimpleName();

        if (daos.containsKey(className)) {
            dao = daos.get(className);
        }
        if (dao == null) {
            dao = super.getDao(clazz);
            daos.put(className, dao);
        }
        D castDao = (D) dao;
        return castDao;
    }


    public interface DBOpenHelperListener {
        void onCreate(ConnectionSource connectionSource);

        //void onUpgrade(ConnectionSource connectionSource, int oldVersion, int newVersiosion);
        void onClearDatebase();
    }
}
